<template>
  <div class="h-full w-full p-5">
    <div class="product-form-container h-full">
      <!-- 表单卡片 -->
      <el-card class="form-card h-full">
        <el-form
          ref="productFormRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="product-form"
          :disabled="formDisabled"
        >
          <!-- 产品名称 -->
          <el-form-item label="产品名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入产品名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <!-- 产品图片 -->
          <el-form-item label="产品图片" prop="imageUrl">
            <el-upload
              list-type="picture-card"
              action="/api/basic/upload/local"
              :on-success="handleImageUploadSuccess"
              :on-error="handleImageUploadError"
              :before-upload="beforeImageUpload"
              :file-list="fileList"
              :limit="1"
              :on-remove="handleFileRemove"
              :headers="{ token: accessStore.accessToken }"
            >
              <!-- 仅当文件列表小于限制时显示添加图标 -->
              <IconifyIcon
                icon="fluent:add-20-regular"
                width="28px"
                height="28px"
              />
              <template #tip>
                <div class="el-upload__tip">
                  支持上传jpg、jpeg、png文件大小不超过20MB
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 产品价格 -->
          <el-form-item label="产品价格" prop="price">
            <el-input-number
              v-model="formData.price"
              placeholder="请输入产品价格"
              :min="0"
              controls-position="right"
              style="width: 32%"
            >
              <template #suffix>元/小时</template>
            </el-input-number>
          </el-form-item>

          <!-- 表单底部按钮 -->
          <el-form-item class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  ElMessage,
  type FormInstance,
  type UploadFile,
  type UploadFiles,
} from 'element-plus';
// 导入Element Plus组件
import {
  ElCard,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElUpload,
  ElInputNumber,
} from 'element-plus';
import { IconifyIcon } from '@vben/icons';
import {
  addProduct,
  getProductById,
  updateProduct,
  type productApi,
} from '#/api/product';
import { useAccessStore } from '@vben/stores';

// 路由相关
const router = useRouter();
const route = useRoute();
const accessStore = useAccessStore();
// 表单状态
const productFormRef = ref<FormInstance | null>(null);
const formDisabled = ref(false);
const formData = reactive<{
  id?: null | string;
  name: string;
  price: null | number;
  imageUrl: string;
}>({
  id: null,
  name: '',
  price: 0,
  imageUrl: '',
});

// 图片上传相关
const fileList = ref<any>([]);

// 判断是否为编辑状态
const isEdit = computed(() => {
  return !!route.params.id;
});

// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入产品价格', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传产品图片', trigger: 'change' }],
});

// 上传前校验图片格式和大小
const beforeImageUpload = (file: File) => {
  // 支持的图片格式
  const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
  // 20MB的字节数
  const maxSize = 20 * 1024 * 1024;

  // 校验格式
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('请上传jpg、jpeg、png格式的图片');
    return false;
  }

  // 校验大小
  if (file.size > maxSize) {
    ElMessage.error('图片大小不能超过20MB');
    return false;
  }

  return true;
};

// 页面加载时处理
onMounted(() => {
  if (isEdit.value) {
    loadProductDetail(route.params.id as string);
  }
});

// 加载产品详情（编辑时）
const loadProductDetail = async (id: string) => {
  formDisabled.value = true;
  try {
    const { code, data } = await getProductById(id);
    if (code == 200) {
      // 转换为表单绑定的格式
      formData.id = data.id;
      formData.name = data.name;
      formData.price = data.price;
      formData.imageUrl = data.imageUrl;
      formDisabled.value = false;
      fileList.value = [{ url: data.imageUrl }];
    }
  } catch (error) {
    ElMessage.error(
      '加载产品详情失败：' + (error as Error).message || '未知错误',
    );
    formDisabled.value = false;
  }
};

// 图片上传成功处理 - 接收后端返回的URL
const handleImageUploadSuccess = (
  response: { data: string; code: number; message: string },
  file: UploadFile,
) => {
  if (response.code === 200 && response?.data) {
    formData.imageUrl = response.data;
    // 更新文件列表显示
    fileList.value = [
      {
        url: response.data,
        name: file.name,
        uid: file.uid,
      },
    ];
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败：' + (response.message || '未返回图片URL'));
  }
};

// 图片上传失败处理
const handleImageUploadError = (error: any) => {
  ElMessage.error('图片上传失败：' + (error.message || '网络错误'));
};

// 处理文件移除
const handleFileRemove = (file: UploadFile, upFileList: UploadFiles) => {
  // 清空表单图片URL
  formData.imageUrl = '';
  // 更新文件列表
  fileList.value = upFileList;
  // 触发表单验证，提示用户需要重新上传
  productFormRef.value?.validateField('imageUrl');
  ElMessage.info('图片已移除，请重新上传');
};

// 提交表单
const handleSubmit = async () => {
  const valid = await productFormRef.value?.validate();
  if (!valid) return;
  formDisabled.value = true;
  try {
    const submitData: productApi.productParams = {
      name: formData.name,
      imageUrl: formData.imageUrl,
      price: formData.price,
    };

    // 如果是编辑状态，需要带上id
    if (isEdit.value && formData.id) {
      submitData.id = formData.id;
    }
    const request = isEdit.value ? updateProduct : addProduct;
    const data = await request(submitData);
    if (data.code == 200) {
      ElMessage.success(data.data);
      router.push('/product/list');
    } else {
      ElMessage.warning(data.message);
    }
  } catch (error) {
    ElMessage.error('操作失败：' + (error as Error).message || '未知错误');
    formDisabled.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.push('/product/list');
};
</script>

<style lang="scss" scoped>
.product-form-container {
  .form-card {
    border: none;
    width: 100%;
  }

  .product-form {
    padding: 20px 20px 0 0;

    .el-form-item {
      margin-bottom: 18px;

      &.form-actions {
        margin-top: 30px;
        display: flex;
        justify-content: center;
        gap: 16px;

        .el-button {
          min-width: 100px;
        }
      }
    }
  }
}
</style>
